module Cms
  class Browser::Icon < Fragment

    attr_accessor :label, :uuid

    def render

      e(:a, :onclick => "
          dcat_instance.oninit(function(Y) {
            Y.io('#{callback :open}?uuid=#{uuid}', {
              method: 'POST',
              on : {
                complete : function(id, o, args) {
                  eval(o.responseText);
                }
              }
            });
          });

        ", :innerHTML => label)
      super()
    end

    def open
      uuid = context.request.params['uuid']
      persisted = Desktop.repo.get(uuid)
      if persisted.object.respond_to? 'uuid='
        persisted.object.uuid = uuid
      end
      rendered = persisted.object.render
      respond "
        jQuery('.desktopContainer').append('#{rendered.join().split("\n").join().split("'").join("\\'")}');
      "
    end
  end
end